#include "LockFreeRingBuffer.h"
#include "OrderPacket.h"
#include <cstring>

template <typename T>
LockFreeRingBuffer<T>::LockFreeRingBuffer(size_t capacity)
    : capacity_(capacity), head_(0), tail_(0)
{
    assert((capacity_ & (capacity_ - 1)) == 0 && "capacity must be power of 2!");
    buffer_ = new T[capacity_];
}

template <typename T>
LockFreeRingBuffer<T>::~LockFreeRingBuffer()
{
    delete[] buffer_;
}

template <typename T>
bool LockFreeRingBuffer<T>::push(const T &item)
{
    size_t head = head_.load(std::memory_order_relaxed);
    size_t next_head = next(head);
    // 检查是否缓冲区已满(实际是缓冲区空一个位置)
    if (next_head == tail_.load(std::memory_order_acquire))
    {
        return false; // full
    }
    buffer_[head] = item;
    head_.store(next_head, std::memory_order_release);
    return true;
}

template <typename T>
bool LockFreeRingBuffer<T>::pop(T &item)
{
    size_t tail = tail_.load(std::memory_order_relaxed);

    if (tail == head_.load(std::memory_order_acquire))
    {
        return false; // empty
    }
    item = buffer_[tail];
    tail_.store(next(tail), std::memory_order_release);
    return true;
}

template <typename T>
bool LockFreeRingBuffer<T>::empty() const
{
    return head_.load(std::memory_order_acquire) == tail_.load(std::memory_order_acquire);
}

template <typename T>
bool LockFreeRingBuffer<T>::full() const
{
    size_t next_head = next(head_.load(std::memory_order_acquire));
    return next_head == tail_.load(std::memory_order_acquire);
}

template <typename T>
size_t LockFreeRingBuffer<T>::size() const
{
    size_t h = head_.load(std::memory_order_acquire);
    size_t t = tail_.load(std::memory_order_acquire);
    return (h + capacity_ - t) & (capacity_ - 1);
}

template <typename T>
size_t LockFreeRingBuffer<T>::next(size_t idx) const
{
    return (idx + 1) & (capacity_ - 1);
}

// 手动实例化（如果单独cpp的话）
template class LockFreeRingBuffer<OrderPacket>;
